const Promise = require('bluebird');
const models = require('../../src/models');
const mysqlConfig = require('../../config').mysql;
const permissions = require('./data/permissions.json');
const permissions_roles = require('./data/permissions_roles.json');
const instance = models.newInstance(mysqlConfig);
const sequelize = instance.sequelize;
const Permissions = instance.Permissions;

sequelize.transaction(function (t) {
    return Promise.map(permissions, function (permission) {
        return Permissions.findOne({
            where: {
                object_type: permission.object_type,
                action_type: permission.action_type
            },
            transaction: t
        }).then(function (p) {
            if (!p) {
                return Permissions.create(permission, {transaction: t}).then(function () {
                    var excutes = [];
                    for (var i in permissions_roles) {
                        var permissions_role = permissions_roles[i];
                        var role = permissions_role.Role, permissions = permissions_role.Permissions;
                        for (var j in permissions) {
                            var ps = permissions[j];
                            if (ps.object_type == permission.object_type && (ps.action_type == 'all' || ps.action_type == permission.action_type)) {
                                var sql = "insert into PermissionsRoles(role, permission_id, created_at, updated_at) " +
                                    "select '" + role + "', id as permission_id, NOW(), NOW() from Permissions where object_type = '" + permission.object_type + "' and action_type in ('" + permission.action_type + "')";
                                excutes.push(sequelize.query(sql, {
                                    type: sequelize.QueryTypes.INSERT, transaction: t
                                }));
                            }
                        }
                    }
                    return Promise.all(excutes);
                });
            }
        });
    }, {concurrency: 1});
});


